//
//  AppDelegate+AppVersion.swift
//  SmartEyeForDoctor
//
//  Created by qdsg on 2021/6/18.
//

import Moya

extension AppDelegate {
    static func requestAppVersionFromAppStore() {
        SEHttpManager.shared.requestForAny(SECommonAPI.appVersionFromAppStore) { result, status in
            SELog(result)
            guard let results = result as? Array<[String : Any]>,
                  results.count > 0,
                  let resultsDict = results.first
            else { return }

            guard let version = resultsDict["version"] as? String,
//                let releaseNotes = resultsDict["releaseNotes"] as? String,
                let updateUrl = resultsDict["trackViewUrl"] as? String
            else { return }

            if self.compareVersion(appstore: version, local: UIDevice.appVersion) {
                SEAlert.showUpdateAlert(title: "您有新版本更新\(version)",
                                        message: resultsDict["releaseNotes"] as? String,
                                        updateUrl: updateUrl,
                                        target: mainWindow?.rootViewController)
            }
        }
    }

    private static func compareVersion(appstore version1: String, local version2: String) -> Bool {
        var numbers1 = version1.split(separator: ".").compactMap { Int(String($0)) }
        var numbers2 = version2.split(separator: ".").compactMap { Int(String($0)) }
        let numDiff = numbers1.count - numbers2.count

        if numDiff < 0 {
            numbers1.append(contentsOf: Array(repeating: 0, count: -numDiff))
        } else if numDiff > 0 {
            numbers2.append(contentsOf: Array(repeating: 0, count: numDiff))
        }

        for i in 0..<numbers1.count {
            let diff = numbers1[i] - numbers2[i]
            if diff != 0 {
                return diff > 0 ? true : false
            }
        }
        return false
    }
}
